package com.kkb.demo.netty.example.selector;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by allenjsl on 2021/2/5.
 */
public class ClientTest {
    private static SocketChannel socketChannel;
    private static Selector selector;
    public ClientTest()throws Exception {
        socketChannel= SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 1234));
        socketChannel.configureBlocking(false);
        selector= Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
    public static void main(String[] args) throws Exception{
        ClientTest test=new ClientTest();

        //创建文件的输入流
        File file = new File("C:\\Users\\allenjsl\\Documents\\app.sql");
        FileInputStream fileInputStream = new FileInputStream(file);

        //通过 fileInputStream 获取对应的 FileChannel -> 实际类型 FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();

        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());

        //将通道的数据读入到 Buffer
        fileChannel.read(byteBuffer);

        fileInputStream.close();

//        ByteBuffer buffer= ByteBuffer.allocate(1024);
//        buffer.put("hello server".getBytes());
        byteBuffer.flip();
        while(byteBuffer.hasRemaining()){
            test.socketChannel.write(byteBuffer);
            byteBuffer.rewind();
            Thread.sleep(100L);
        }

        byteBuffer.clear();
        socketChannel.socket().shutdownOutput();

        String response=receiveData(test.socketChannel);
        System.out.println(response);
    }

    public static String receiveData(SocketChannel socketChannel2) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String response = "";
        try {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            byte[] bytes;
            int count = 0;
            while ((count = socketChannel2.read(buffer)) >= 0) {
                buffer.flip();
                bytes = new byte[count];
                buffer.get(bytes);
                baos.write(bytes);
                buffer.clear();
            }

            bytes = baos.toByteArray();
            response = new String(bytes);
        } finally {
            try {
                baos.close();
            } catch (Exception ex) {
            }
        }
        return response;
    }
}
